import React, {useState, useEffect, useRef} from 'react';
import {Input, Button, Avatar} from '@taroify/core';
import './index.module.scss';
import {formatTime} from './utils';
import {ScrollView, View} from '@tarojs/components';
import styles from "./index.module.scss";
import avatarSrc from "@/app/asserts/avatar.jpg"

const ChatPage: React.FC = () => {
    const [messages, setMessages] = useState<any[]>([
        {
            messageId: '1',
            from: 1, // 对方发送
            content: '你好！我是张三 😊',
            time: Date.now() - 120000, // 2分钟前
            read: true,
        },
        {
            messageId: '2',
            from: 0, // 自己发送
            content: '你好！很高兴认识你～',
            time: Date.now() - 60000, // 1分钟后
            read: true,
        },
        {
            messageId: '3',
            from: 1, // 对方发送
            content: '最近在学习 Taro 和 React 开发小程序，一起交流吧！',
            time: Date.now() - 30000, // 半分钟前
            read: true,
        },
    ]);

    const [input, setInput] = useState('');
    const [keyboardHeight, setKeyboardHeight] = useState(0);
    const [userId, setUserId] = useState<string | null>(null);
    const [name, setName] = useState<string>('用户');

    useEffect(() => {
        // 模拟 onLoad 获取数据
        // const openerEventChannel = {on: (event, handler) => handler({userId: '123', avatar, name: '张三'})};
        // openerEventChannel.on('update', (data) => {
        //     setUserId(data.userId);
        //     setAvatar(data.avatar);
        //     setName(data.name);
        //     setMessages([...data.messages]);
        // });
        //
        // return () => {
        //     // 模拟卸载事件监听
        // };
    }, []);

    const sendMessage = () => {
        if (!input.trim()) return;

        const newMessage = {
            messageId: null,
            from: 0,
            content: input,
            time: Date.now(),
            read: true,
        };

        const updatedMessages = [...messages, newMessage];
        setMessages(updatedMessages);
        setInput('');

        // 模拟发送消息到 socket
        console.log('发送消息:', {type: 'message', data: {userId, content: input}});
        setTimeout(() => {
            // 滚动到底部
            scrollToBottom();
        }, 0);
    };

    const handleInput = (e) => {
        setInput(e.detail.value);
    };

    const handleKeyboardHeightChange = (e) => {
        const {height} = e.detail;
        setKeyboardHeight(height);
        setTimeout(scrollToBottom, 0);
    };

    const handleBlur = () => {
        setKeyboardHeight(0);
    };

    const scrollToBottom = () => {
        // 实现滚动到底部逻辑（需结合 DOM 或 ref）
    };

    return (
        <View className={styles.page}>
            <ScrollView
                className={styles.content}
                scrollY
                scrollWithAnimation
                scrollTop={99999}
            >
                <View className={styles.messages}>
                    {messages.map((msg, index) => {
                        const showTime = index === 0 || (messages[index - 1] && msg.time - messages[index - 1].time > 120000);
                        return (
                            <React.Fragment key={index}>
                                {showTime && <View className={styles.time}>{formatTime(msg.time)}</View>}
                                {msg.from === 0 ? (
                                    <View className={`${styles.message_area}`}>
                                        <View className={`${styles.message} ${styles.self}`}>
                                            {msg.content}</View>
                                        <Avatar src={avatarSrc} size="medium"/>

                                    </View>
                                ) : (
                                    <View className={`${styles.message_area}`}>
                                        <Avatar src={avatarSrc} size="medium"/>
                                        <View className={`${styles.message} ${styles.other}`}>
                                            {msg.content}</View>
                                    </View>
                                )}
                            </React.Fragment>
                        );
                    })}
                    <View id="bottom"/>
                </View>
            </ScrollView>

            <View className={styles.bottom}>
                <View className={styles.input}>
                    <Input
                        value={input}
                        type="text"
                        placeholder="请输入..."
                        confirmType="send"
                        onInput={handleInput}
                        onConfirm={sendMessage}
                        onFocus={handleKeyboardHeightChange}
                        onBlur={handleBlur}
                        className={styles.input_input}
                    />
                </View>
                <Button className={styles.send} color="primary" shape="round" onClick={sendMessage} disabled={!input}>
                    发送
                </Button>
            </View>
        </View>
    );
};

export default ChatPage;
